package worker

import (
	"Doge/models"
	"Doge/modules/delayed/common"
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// mysql存储日志
type LogSink struct {
	client *gorm.DB
	logChan chan *common.JobLog
	autoCommitChan chan *common.LogBatch
}

var (
	// 单例
	G_logSink *LogSink
)



// 日志存储协程
func (logSink *LogSink) writeLoop() {
	var (
		log *common.JobLog
		jobLog *models.Delayed
		jobLogByte []byte
		err error
	)

	for {
		select {
		case log = <- logSink.logChan:
			if jobLogByte, err = json.Marshal(log); err != nil {
				return
			}

			jobLog = &models.Delayed{
				Log:      string(jobLogByte),
				Status:   1,
			}
			logSink.client.Model(&models.Delayed{
				ID: log.JobName,
			}).UpdateColumns(jobLog)
		}
	}
}

func InitLogSink() (err error) {
	var (
		client *gorm.DB
		dsn string
	)
	dsn = G_config.DbUser + ":" + G_config.DbPassword + "@tcp(" + G_config.DbHost + ":" + G_config.DbPort + ")/" + G_config.DbName + "?charset=utf8mb4&parseTime=True&loc=Local"
	if client, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	}); err != nil {
		fmt.Println("连接db报错：", err.Error())
		panic(err)
	}

	//   选择db和collection
	G_logSink = &LogSink{
		client: client,
		logChan: make(chan *common.JobLog, 1000),
		autoCommitChan: make(chan *common.LogBatch, 1000),
	}

	// 启动一个mongodb处理协程
	go G_logSink.writeLoop()
	return
}

// 发送日志
func (logSink *LogSink) Append(jobLog *common.JobLog) {
	select {
	case logSink.logChan <- jobLog:
	default:
		// 队列满了就丢弃
	}
}
